package leetcode.code0767;

import java.util.ArrayList;
import java.util.List;

import leetcode.IDebug;
import leetcode.helper.H;

public class Solution implements IDebug {

//	给定一个字符串 s ，检查是否能重新排布其中的字母，使得两相邻的字符不同。
//
//	返回 s 的任意可能的重新排列。若不可行，返回空字符串 "" 。

	public String reorganizeString(String s) {
		char[] cs = s.toCharArray();
		int len = cs.length;
		int[] hash = new int[26];
		for (int i = 0; i < cs.length; i++) {
			int c = cs[i] - 'a';
			hash[c]++;
		}
		int big = 0, index = 0;
		for (int i = 0; i < hash.length; i++) {
			int num = hash[i];
			if (num > big) {
				big = num;
				index = i;
			}
		}
		if (big > (len + 1) / 2) {
			return "";
		}
		List<Integer>[] bucket = new ArrayList[big];
		for (int i = 0; i < bucket.length; i++) {
			bucket[i] = new ArrayList<>();
			bucket[i].add(index);
		}
		for (int i = 0, p = 0; i < hash.length; i++) {
			int num = hash[i];
			if (num != 0 && i != index) {
				for (int j = 0; j < num; j++) {
					bucket[p].add(i);
					p = p == big - 1 ? 0 : p + 1;
				}
			}
		}
		char[] ans = new char[len];
		for (int i = 0, j = 0; i < big; i++) {
			List<Integer> list = bucket[i];
			for (int c : list) {
				ans[j++] = (char) (c + 'a');
			}
		}
		return new String(ans);
	}

	@Override
	public void debug4() {
		H.compare("aba", this.reorganizeString("aab"));
		H.compare("acacabcb", this.reorganizeString("aaabbccc"));

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
